package day11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试读写锁
public
class TestReadWrite {
    Object data;//数据
    ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();//读写锁

    public
    void read() {

        try {
            rwl.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "开始读取2s数据中：" + data);
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + "读取2s完毕：" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rwl.readLock().unlock();
        }
    }
    public
    void write(Object data) {
        try {
            rwl.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "开始写入数据中：" + data);
            this.data = data;
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName() + "写入数据完毕：" + data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            rwl.writeLock().unlock();
        }


    }

    public static
    void main(String[] args) {
        TestReadWrite t = new TestReadWrite();
        for (int i = 1; i < 3; i++) {//写入
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    t.write(System.currentTimeMillis());
                }
            }, "线程" + i + "").start();
        }
        for (int i = 3; i < 5; i++) {//读取
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    t.read();
                }
            }, "线程" + i + "").start();
        }
    }
}
